package com.example.taluo.security;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/*** @Author supersaiya
 * @Description token拦截器

 * @Date 2025/2/12 17:25

 * @Version 1.0*/

@Component
public class TokenFilter implements Filter {
    private static final List<String> EXCLUDED_PATHS = Arrays.asList("/api/auth/login");

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String path = httpRequest.getRequestURI();

        // 检查是否排除该路径
        if (isExcludedPath(path)) {
            chain.doFilter(request, response);  // 放行
            return;
        }

        // 获取并验证Token
        String token = httpRequest.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7); // 去掉Bearer前缀
            TokenProvider tokenProvider = new TokenProvider();
            if (!tokenProvider.validateToken(token)) {
                throw new ServletException("Invalid token");
            }
        }

        chain.doFilter(request, response);
    }

    private boolean isExcludedPath(String path) {
        return EXCLUDED_PATHS.stream().anyMatch(excludedPath -> path.contains(excludedPath));
    }
}